#include <QtGui>
#include <QFileDialog>

#include "configedit.h"
#include "lib/config.h"

#include <cerrno>
#include <csignal>

ConfigEdit::ConfigEdit () 
  : QMainWindow()
{
  memset(&serverConfig, 0, sizeof(serverConfig));
  ui.setupUi(this);
  connect(ui.buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked(bool)), this, SLOT(apply()));
}


ConfigEdit::~ConfigEdit()
{

}

void ConfigEdit::cancel()
{
  /* TODO: quit gracefully */
  exit(0);
}

void ConfigEdit::apply()
{
  updateConfig();
  saveConfigIn(fileName);
  if (serverConfig.pid > 1)
    kill(serverConfig.pid, SIGUSR2);
}


void ConfigEdit::openConfigFile()
{
  fileName = QFileDialog::getOpenFileName(this, "Chose the configuration file");
  QFileInfo info(fileName);
  ui.statusbar->showMessage(tr("Working on file ") + info.fileName());
  
  loadConfigFrom(fileName);
}

void ConfigEdit::showEvent (QShowEvent *ev)
{
  QMainWindow::showEvent(ev);
  QString message = tr("Open a configuration file to edit using the File menu.");
  ui.statusbar->showMessage(message, -1);
}




void ConfigEdit::loadConfigFrom (QString &fileName)
{
  int error = 0;
  if (fileName.isEmpty())
    return;
    
  error = serverconfig_load(fileName.toAscii().constData(), &serverConfig);
  if (error)
  {
    statusBar()->showMessage(tr("Error while loading config from ") + fileName, -1);
  }
  else
  {
    statusBar()->showMessage(tr("Config loaded from ") + fileName, -1);
    ui.centralwidget->setEnabled(true);
    updateForm();
  }
}

void ConfigEdit::saveConfigIn (QString& fileName)
{
  int error = 0;
  if (fileName.isEmpty())
    return;
  
  error = serverconfig_save(fileName.toAscii().constData(), &serverConfig);
  if (error)
  {
    statusBar()->showMessage(tr("Error while saving config to ") + fileName, -1);
  }
  else
  {
    statusBar()->showMessage(tr("Config saved to ") + fileName, -1);
    centralWidget()->setEnabled(true);
    updateForm();
  }
}

void ConfigEdit::updateForm()
{
  ui.documentRootLineEdit->setText(QString(serverConfig.root));
  ui.standardPortSpinBox->setValue(serverConfig.port);
  ui.maximumSpeedSpinBox->setValue(serverConfig.speed);
}

void ConfigEdit::updateConfig()
{
  serverConfig.port = ui.standardPortSpinBox->value();
  serverConfig.speed = ui.maximumSpeedSpinBox->value();
  strcpy(serverConfig.root, ui.documentRootLineEdit->text().toAscii().data());
}


void ConfigEdit::selectRootPath()
{
  QString rootPath = QFileDialog::getExistingDirectory(this, "Select a root directory for the server");
  ui.documentRootLineEdit->setText(rootPath);
}

void ConfigEdit::killServer()
{
  QString message;
  
  kill(serverConfig.pid, SIGINT);
  
  if (kill(serverConfig.pid, 0) == 0)
  {
    ui.statusbar->showMessage(tr("PID ") + QString::number(serverConfig.pid) + " Killed.");
    centralWidget()->setEnabled(false);
  } else {
    ui.statusbar->showMessage(tr("Cannot kill ") + QString::number(serverConfig.pid) + ": " + strerror(errno));
  }
}





